package com.youhui.weixin.websocket;

import com.youhui.weixin.common.MythConfig;
import lombok.extern.log4j.Log4j;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import java.io.IOException;
import java.net.URI;

/**
 * WebSocket客户端.
 *
 * @author: huang
 * Date: 17-11-15
 */
@Component
@Log4j
@ClientEndpoint
public class WebSocketClient {

    private Session session;

    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
    }

    @OnMessage
    public void onMessage(String text) throws IOException {
        session.getBasicRemote().sendText(text);
    }

    @OnError
    public void onError(Throwable throwable) {
        log.error(throwable.getMessage());
    }

    @OnClose
    public void onClosing() throws IOException {
//        log.info("连接关闭");
        session.close();
    }

    public void sendMessage(String toId, String text) throws IOException {
        text = toId + MythConfig.SOCKET_MESSAGE + text;
//        log.info(text);
        onMessage(text);
    }

    public static WebSocketClient connect(String url) throws Exception {
        WebSocketContainer wsc = ContainerProvider.getWebSocketContainer();
        WebSocketClient client = new WebSocketClient();
        wsc.connectToServer(client, new URI(url));
        return client;
    }

}
